import CustomNavBar from '@/components/CustomNavBar/CustomNavBar.vue';
import CustomTabBar from '@/components/CustomTabBar/CustomTabBar.vue';
import api from '@/http/api.js';
import detectEthereumProvider from '@metamask/detect-provider';
import Web3 from 'web3';
import {
	NETWORKS
} from '@/src/config/networks.js';
import {formatNumber} from '@/src/utils/common.js'
// 提领合约 ABI 片段
const ERC20_ABI = [
	// 代币元数据
	{
		"constant": true,
		"inputs": [],
		"name": "name",
		"outputs": [{
			"name": "",
			"type": "string"
		}],
		"type": "function"
	},
	{
		"constant": true,
		"inputs": [],
		"name": "symbol",
		"outputs": [{
			"name": "",
			"type": "string"
		}],
		"type": "function"
	},
	{
		"constant": true,
		"inputs": [],
		"name": "decimals",
		"outputs": [{
			"name": "",
			"type": "uint8"
		}],
		"type": "function"
	},

	// 余额查询
	{
		"constant": true,
		"inputs": [{
			"name": "owner",
			"type": "address"
		}],
		"name": "balanceOf",
		"outputs": [{
			"name": "",
			"type": "uint256"
		}],
		"type": "function"
	},

	// 转账
	{
		"constant": false,
		"inputs": [{
				"name": "to",
				"type": "address"
			},
			{
				"name": "value",
				"type": "uint256"
			}
		],
		"name": "transfer",
		"outputs": [{
			"name": "",
			"type": "bool"
		}],
		"type": "function"
	},

	// 授权相关
	{
		"constant": false,
		"inputs": [{
				"name": "spender",
				"type": "address"
			},
			{
				"name": "value",
				"type": "uint256"
			}
		],
		"name": "approve",
		"outputs": [{
			"name": "",
			"type": "bool"
		}],
		"type": "function"
	},
	{
		"constant": true,
		"inputs": [{
				"name": "owner",
				"type": "address"
			},
			{
				"name": "spender",
				"type": "address"
			}
		],
		"name": "allowance",
		"outputs": [{
			"name": "",
			"type": "uint256"
		}],
		"type": "function"
	},
	{
		"constant": false,
		"inputs": [{
				"name": "from",
				"type": "address"
			},
			{
				"name": "to",
				"type": "address"
			},
			{
				"name": "value",
				"type": "uint256"
			}
		],
		"name": "transferFrom",
		"outputs": [{
			"name": "",
			"type": "bool"
		}],
		"type": "function"
	},

	// 事件
	{
		"anonymous": false,
		"inputs": [{
				"indexed": true,
				"name": "from",
				"type": "address"
			},
			{
				"indexed": true,
				"name": "to",
				"type": "address"
			},
			{
				"indexed": false,
				"name": "value",
				"type": "uint256"
			}
		],
		"name": "Transfer",
		"type": "event"
	},
	{
		"anonymous": false,
		"inputs": [{
				"indexed": true,
				"name": "owner",
				"type": "address"
			},
			{
				"indexed": true,
				"name": "spender",
				"type": "address"
			},
			{
				"indexed": false,
				"name": "value",
				"type": "uint256"
			}
		],
		"name": "Approval",
		"type": "event"
	}
];
export default {
	components: {
		CustomNavBar,
		CustomTabBar
	},
	data() {
		return {
			web3: null,
			provider: null,

			currentPage: 'pages/My/index', //tabar跳转路径
			account: null, //账户地址
			chainType: null, //链类型
			withdrawAmount: null, //提领数量

			withdrawableBalance: '0', //可提领余额
			contractAddress: '', //合约地址
			txHash: '',

			assetsData: [], //资产详情
			cointype: '', //币种

			withdrawalButtonisShow: true, //按钮禁用
			
			
		}
	},
	onLoad() {
		this.getCointype();
	},
	onShow() {
		//this.loadWithdrawableBalance();
		this.loadD();
	},
	async mounted() {
		//获取合约地址
		await this.treatyAddress();
		//初始化web3
		await this.initWeb3();
		//获取余额
		this.loadWithdrawableBalance();

		//初始化数据
	},
	computed: {
		currencyType() {
			return this.$userInfo.cointype
		},
		//账户
		nowSubAccount() {
			if (!this.$userInfo.nowSubAccount) {
				return
			}
			let account = this.$userInfo.nowSubAccount[0].substring(0, 6) + '****' + this.$userInfo.nowSubAccount[0]
				.substring(this.$userInfo.nowSubAccount[0].length -
					7, this.$userInfo.nowSubAccount[0].length);
			return account;
		},
	},
	methods: {
		//初始化数据
		async loadD() {
			const provider = await detectEthereumProvider();
			if (!provider) return false;

			// 1. 静默获取当前账户（不会弹出授权窗口）
			const accounts = await provider.request({
				method: 'eth_accounts'
			});

			//获取当前网络chainType
			const chainId = await provider.request({
				method: 'eth_chainId'
			});

			if (chainId == '0x1') {
				this.chainType = 'erc'
			} else if (chainId == '0x38') {
				this.chainType = 'bsc'
			}
			
			//更新当前动态管理的币种
			this.getCointype();

			//获取资产情况
			api.assetDetails({
				address: accounts[0],
				chaintype: this.chainType,
				cointype: this.$userInfo.cointype
			}).then(res => {
				if (res.code == 1) {
					this.assetsData = res.data;
					
					//处理字符串、数值
					this.assetsData.today_reward_lockup = formatNumber(this.assetsData.today_reward_lockup)
				    this.assetsData.total_reward_lockup = formatNumber(this.assetsData.total_reward_lockup)
					this.assetsData.lockup_balance = formatNumber(this.assetsData.lockup_balance)
					this.assetsData.platform_usdt = formatNumber(this.assetsData.platform_usdt)
					this.assetsData.pool_balance = formatNumber(this.assetsData.pool_balance)
					this.assetsData.withdraw_usdt = formatNumber(this.assetsData.withdraw_usdt) 
				} else {
					uni.showToast({
						title: res.msg,
						icon: 'none'
					})
				}
			})
		},
		//获取币种
		getCointype(){
			this.cointype = this.$userInfo.cointype;
		},
		//可提领余额是否空判断
		isbalance(){
			let num = Number(this.assetsData.platform_usdt) === 0;
			return num
		},
		//提领
		toWithdrawal() {
			//根据余额判断提领事件是否禁用
			let num = Number(this.assetsData.platform_usdt) === 0;
			if(num){
				return
			}
			if(!this.withdrawAmount ||this.withdrawAmount==0){
				uni.showToast({
					title:this.$t('My.characters18'),
					icon:'none'
				})
				return
			}
			
			this.withdrawalButtonisShow = false;
			api.Collar({
				address: this.$userInfo.nowSubAccount[0],
				token_num: this.withdrawAmount,
				chaintype: this.$userInfo.chainType,
				cointype: this.$userInfo.cointype
			}).then(res => {
				if(res.code==1){
					uni.showToast({
						title: res.msg,
						icon: 'none'
					})
				}else{
					uni.showToast({
						title: res.msg,
						icon: 'none'
					})
				}
			})
			this.withdrawalButtonisShow = true;
			setTimeout(res=>{
				window.location.reload();
			},2000)
			
		},

		// 初始化 Web3 和 MetaMask 检测
		async initWeb3() {
			this.provider = await detectEthereumProvider();
			if (this.provider) {
				this.web3 = new Web3(this.provider);
				//this.provider.on('accountsChanged', this.handleAccountsChanged);
				const accounts = await this.web3.eth.getAccounts();
				this.account = accounts[0] || '';
			}
		},
		//获取余额
		async loadWithdrawableBalance() {
			const contract = new this.web3.eth.Contract(
				ERC20_ABI,
				this.contractAddress
			);
			const balance = await contract.methods
				.balanceOf(this.account)
				.call();
			this.withdrawableBalance = this.web3.utils.fromWei(balance, 'ether');
		},
		//获取合约地址
		async treatyAddress() {
			const provider = await detectEthereumProvider();
			// 获取当前网络
			const chainId = await provider.request({
				method: 'eth_chainId'
			});
			const currentNetwork = Object.values(NETWORKS).find(
				net => net.chainId === chainId
			);
			console.log('sca', currentNetwork)
			this.contractAddress = currentNetwork.tokens.USDC.address;
		},
		//处理提领
		async handleWithdraw() {
			try {
				const contract = new this.web3.eth.Contract(
					ERC20_ABI,
					this.contractAddress
				);

				// 动态获取小数位
				const decimals = await contract.methods.decimals().call();
				const amountInWei = this.web3.utils.toWei(this.withdrawAmount, 'ether');

				// 发送提领交易
				const tx = contract.methods
					.transfer(this.account, amountInWei)
					.send({
						from: this.account
					});

				tx.on('transactionHash', (hash) => {
					this.txHash = hash;
				});

				await tx;
				uni.showToast({
					title: '提领成功'
				});

				// 刷新余额
				await this.loadWithdrawableBalance();
			} catch (error) {
				console.log(error)
				uni.showToast({
					title: `提领失败: ${error.message}`,
					icon: 'none'
				});
			} finally {

			}
		},
		async loadData() {
			const provider = await detectEthereumProvider();
			// 1. 静默获取当前账户（不会弹出授权窗口）
			const accounts = await provider.request({
				method: 'eth_accounts'
			});

			// 2. 检查是否有已连接的账户
			if (accounts.length > 0) {
				this.account = accounts[0];
			}
			// 获取当前网络
			const chainId = await provider.request({
				method: 'eth_chainId'
			});
			if (chainId == '0x1') {
				this.chainType = 'erc'
			} else if (chainId == '0x38') {
				this.chainType = 'bsc'
			}
			// api.getassets({
			// 	address:this.account,
			// 	chaintype:this.chainType,
			// 	cointype:this.$userInfo.cointype || 'USDT',
			// }).then(res=>{

			// }).catch(err=>{
			// 	console.log(err)
			// })
		},
		Income() {
			uni.navigateTo({
				url: '/pages/My/IncomeRecord/index'
			})
		},
		CashWithdrawal() {
			uni.navigateTo({
				url: '/pages/My/CashWithdrawalRecord/index'
			})
		}
	},

}